import {
  createSlice,
  createAsyncThunk // 创建一个异步action
} from '@reduxjs/toolkit';

// 请求
export const iqiyiMoviesAPI = () => fetch('https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=11&page_id=2&ret_num=48').then(res => res.json());
export const getNestUser = () => fetch('/nestApi/user/getUser').then(res => res.json());

// 创建一个异步请求
export const loadAsyncData = createAsyncThunk(
  // 命名空间
  'asyncCountSlice/loadAsyncData',
  // 发出一个请求
  // async () => {
  //   const movies = await iqiyiMoviesAPI()
  //   const users = await getNestUser()
  //   return {users, movies}
  // },
  // 此处需要返回一个Promise数据
  async payload => {
    try {
      const movies = await iqiyiMoviesAPI();
      const users = await getNestUser();
      return { users, movies };
    } catch (error) {
      throw new Error('发生错误！！！');
    }
  }
);

const consoleStyle = 'color: red;font-size: 24px;';
//
export const asyncSlice = createSlice({
  name: 'asyncCountSlice',
  initialState: {
    name: 'asyncThunkState',
    userList: [],
    movieSlice: []
  },
  reducers: {
    addAsyncUser(state, payload) {
      return (state.userList = payload.userList);
    }
  },
  // 处理异步请求结果的 reducer
  // extraReducers: (builder) => {
  //   console.log('%c此处在初始化时会自动执行！！！', consoleStyle)
  //   // console.log('asyncThunk extraReducers', builder)
  //   builder.addCase(loadAsyncData.pending, (state, action) => {
  //     console.log('%c异步请求进行中', 'color: yellow; font-size: 20px', state.name, );
  //   }),
  //   builder.addCase(loadAsyncData.fulfilled, (state, action) => {
  //     console.log(action, 'action', );
  //     return {
  //       userList: action.payload.users.data,
  //       movieSlice: action.payload.movies
  //     }
  //   }),
  //   builder.addCase(loadAsyncData.rejected, (state, err) => {
  //     console.log('%c异步请求错误','color: red; font-size: 20px', err);
  //   })
  // },
  // 推荐使用
  // 用于接收异步操作的 reducer 选项
  extraReducers: {
    // 异步请求进行中 pedding
    [loadAsyncData.pending](state) {
      console.log('%c异步请求进行中', 'color: yellow; font-size: 20px', state.name);
    },
    // 请求成功！！！
    [loadAsyncData.fulfilled](state, { payload }) {
      console.log(state, payload);
      return {
        userList: payload.users.data,
        movieSlice: payload.movies
      };
    },
    // 异步请求 错误
    [loadAsyncData.rejected](state, err) {
      console.log('%c异步请求错误', 'color: red; font-size: 20px', err);
    }
  }
});

export const { actions } = asyncSlice;

const asyncReducer = asyncSlice.reducer;
export default asyncReducer;
